package com.cn.kabalifeuser.ui.my.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.cn.kabalifeuser.R;
import com.cn.kabalifeuser.base.IBaseActivity;
import com.cn.kabalifeuser.config.CustomRefreshListener;
import com.cn.kabalifeuser.config.LoginHelper;
import com.cn.kabalifeuser.config.RefreshHelper;
import com.cn.kabalifeuser.ui.integral.bean.DefaultAddressBean;
import com.cn.kabalifeuser.ui.login.bean.MsgBean;
import com.cn.kabalifeuser.ui.my.bean.AddressListBean;
import com.cn.kabalifeuser.ui.my.bean.AddressProvinceListBean;
import com.cn.kabalifeuser.utils.RxToast;
import com.cn.kabalifeuser.utils.TimeUtils;
import com.cn.kabalifeuser.view.NotDataView;
import com.kongzue.dialog.v2.SelectDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by 晓林 on 2020/9/3.
 * function:
 */
public class IAddressListActivity extends IBaseActivity<IAddressView, IAddressPresenter> implements IAddressView {
    @BindView(R.id.rv_notice)
    RecyclerView rvAddresList;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;


    private View notDataView;
    List<AddressListBean.ResultBean.DataBean> mList;
    ListAdapter mAdapter;
    int itemPosition = -1;
    int itemIsSign = 0;
    int sign;
    Bundle bundle;


    @Override
    protected IAddressPresenter createPresenter() {
        return new IAddressPresenter();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_address_list;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        setTitleBar("收货地址");
        bundle = getIntent().getExtras();
        sign = bundle.getInt("sign");
        mList = new ArrayList<>();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getMe());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        layoutManager.setSmoothScrollbarEnabled(true);
        layoutManager.setAutoMeasureEnabled(true);
        rvAddresList.setLayoutManager(layoutManager);
        rvAddresList.setNestedScrollingEnabled(false);

        //创建适配器
        mAdapter = new ListAdapter(R.layout.activity_address_list_item, mList);
        //给RecyclerView设置适配器
        rvAddresList.setAdapter(mAdapter);
        notDataView = NotDataView.notDataView(this, rvAddresList, refreshLayout, "您还没有添加地址信息快去新增吧");
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (sign == 110) {
                    AddressListBean.ResultBean.DataBean bean = mAdapter.getItem(position);
                    Intent intent = new Intent();
                    intent.putExtra("addressId", bean.getId());
                    intent.putExtra("addressName", bean.getName());
                    intent.putExtra("addressPhone", bean.getPhone());
                    intent.putExtra("address", bean.getAddress());
                    setResult(110, intent);
                    finish();
                }
            }
        });
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                AddressListBean.ResultBean.DataBean bean = mAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.ll_btn_check:
                        //设置为默认
                        itemPosition = position;
                        //默认地址
                        mPresenter.onAddressData(LoginHelper.getLonginData().getResult(), mAdapter.getItem(position).getId());
                        break;
                    case R.id.tv_btn_delete:
                        SelectDialog.show(getMe(), "提示", "确定要刪除该地址吗？", "确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                itemPosition = position;
                                itemIsSign = 1;
                                mPresenter.onAddressAddData(
                                        bean.getName(),
                                        bean.getPhone(),
                                        bean.getProvince_id(), bean.getCity_id(), bean.getArea_id(), bean.getStreet_id(), bean.getInfo(),
                                        "del", bean.getId()
                                );
                            }
                        }, "取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });

                        break;
                    case R.id.tv_btn_ed:
                        Bundle bundle = new Bundle();
                        bundle.putInt("sign", bean.getId());
                        bundle.putSerializable("addressBean", bean);
                        $startActivity(IAddressAddActivity.class, bundle);
                        break;
                }
            }
        });
    }

    @OnClick(R.id.tv_btn_next)
    public void onViewClicked() {
        Bundle bundle = new Bundle();
        bundle.putInt("sign", -1);
        $startActivity(IAddressAddActivity.class, bundle);
    }

    @Override
    public void initRefreshLayout() {
        super.initRefreshLayout();
        RefreshHelper.initRefreshLayout(refreshLayout, new CustomRefreshListener() {
            @Override
            public void _onRefresh(RefreshLayout refreshLayout) {
                pagehttp = 1;
                getListData();
            }

            @Override
            public void _onLoadMore(RefreshLayout refreshLayout) {

                if (null != mList) {
                    pagehttp++;
                    getListData();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getListData();
    }

    /**
     * 获取数据。刷新
     */
    public void getListData() {
        //TODO
        mPresenter.onAddressListData(LoginHelper.getLonginData().getResult(), pagehttp, pageNum);
    }

    @Override
    public void onReLoggedIn(String msg) {
        RxToast.error(msg);
        LoginHelper.againGoToLoginActivity(getMe());
    }

    @Override
    public void onError(String msg) {
        RxToast.error(msg);
    }

    @Override
    public Context _getContext() {
        return null;
    }

    @Override
    public void onAddressAddSuccess(MsgBean bean) {
        RxToast.success(bean.getMsg());
        refreshLayout.autoRefresh();
    }

    @Override
    public void onAddressSuccess(DefaultAddressBean bean) {
        mAdapter.refreshItem(itemPosition);
    }


    @Override
    public void onProvinceListSuccess(AddressProvinceListBean bean) {

    }

    @Override
    public void onCityListSuccess(AddressProvinceListBean bean) {

    }


    @Override
    public void onAddressListSuccess(AddressListBean bean) {
        RefreshHelper.finishRefresh(refreshLayout, pagehttp);
        if (pagehttp == 1) {
            if (bean.getResult() != null && bean.getResult().getData().size() > 0) {
                mAdapter.replaceData(bean.getResult().getData());
                mAdapter.refreshItem(0);
            } else {
                mAdapter.replaceData(bean.getResult().getData());
                mAdapter.setEmptyView(notDataView);
            }
        } else {
            if (bean.getResult().getData().size() > 0) {
                mAdapter.addData(bean.getResult().getData());
            }
        }
    }
//    @Override
//    public void onAddressDeleteSuccess(MsgBean bean) {
//        if (itemIsSign == 0)
//            //修改默认、
//            mAdapter.refreshItem(itemPosition);
//        else {
////            mAdapter.remove(itemPosition);
//            pagehttp = 1;
//            getListData();
//        }
//    }


    class ListAdapter extends BaseQuickAdapter<AddressListBean.ResultBean.DataBean, BaseViewHolder> {
        private int selectedPos = -1;
        private int oldPos = -1;

        public ListAdapter(int layoutResId, @Nullable List<AddressListBean.ResultBean.DataBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, final AddressListBean.ResultBean.DataBean item) {
            helper.addOnClickListener(R.id.tv_btn_delete);
            helper.addOnClickListener(R.id.tv_btn_ed);
            helper.addOnClickListener(R.id.ll_btn_check);
            helper.setText(R.id.tv_name, item.getName())
                    .setText(R.id.tv_phone, item.getPhone())
                    .setText(R.id.tv_address, item.getProvince() + item.getCity() + item.getArea() + item.getStreet() + item.getInfo());
//
            ImageView img_check = helper.getView(R.id.img_check);
            if (selectedPos == helper.getPosition()) {
                //相同设置高亮
                img_check.setImageResource(R.drawable.check_true);
            } else {
                //不同设置
                img_check.setImageResource(R.drawable.check_false);
            }

        }

        public void refreshItem(int position) {
            if (selectedPos != -1) {
                oldPos = selectedPos;
            }
            selectedPos = position;
            if (oldPos != -1) {
                notifyItemChanged(oldPos);
            }
            notifyItemChanged(selectedPos);
        }

    }
}
